# utils/http_client.py
import requests
import logging
from requests.exceptions import RequestException
from requests.auth import HTTPBasicAuth

class HttpClient:
    def __init__(self, base_url, headers=None):
        self.base_url = base_url.rstrip('/')
        self.headers = headers or {}
        self.session = requests.Session()
        self.session.headers.update(self.headers)
    
    def _request(self, method, endpoint, params=None, auth=None, **kwargs):
        url = f'{self.base_url}/{endpoint.lstrip("/")}'
        try:
            response = self.session.request(method, url, params=None, auth=auth, **kwargs)
            response.raise_for_status()     # 如果响应状态码不是 200，抛出异常
            logging.info(f"{method} {url} - Response Status: {response.status_code}")
            return response.json()          # 假设响应是 JSON 格式
        except RequestException as e:
            logging.error(f"Error during {method} request to {url}: {e}")
            return None
    # http methods
    # The request's query parameters.
    def get(self, endpoint, params=None, auth=None, **kwlargs):
        return self._request('GET', endpoint, params=params, **kwlargs)
    
    # The request's POST parameters.
    def post(self, endpoint, data=None, json=None, auth=None, **kwargs):
        return self._request('POST', endpoint, json=json, **kwargs)
    
    # The request's PUT parameters.
    def put(self, endpoint, data=None, json=None, auth=None, **kwargs):
        return self._request('PUT', endpoint, json=json, **kwargs)
    
    # The request's DELETE parameters.
    def delete(self, endpoint, auth=None, **kwargs):
        return self._request('DELETE', endpoint, **kwargs)
    # The request's PATCH parameters.    
